<?php

namespace app\admin\model;

use EasyWeChat\Factory;
use think\Cache;
use think\Model;

class AuthDepartment extends Model
{
    // 表名
    protected $name = 'auth_department';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    protected $resultSetType = 'collection';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    public static $app;
    // 追加属性
    protected $append = [
        'delete_status_text'
    ];

    /**
     * 初始化
     */
    public function initialize()
    {
        self::$app = Factory::work(Admin::config());
    }

    public function getDeleteStatusList()
    {
        return ['0' => __('正常'),'1' => __('禁用')];
    }

    public function getDeleteStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['delete_status'];
        $list = $this->getDeleteStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public static function addDep($data)
    {
        return  self::$app->department->create($data);
    }

    public static function updateDep($id,$data)
    {
        return self::$app->department->create($id,$data);
    }

    public static function deleteDep($id)
    {
        return self::$app->department->delete($id);
    }

    public static function DepList()
    {
        if(!$list = Cache::get('departmentList'))
        {
            $list = self::$app->department->list();
            Cache::set('departmentList',$list,589400);//7天有效
        }
        return $list;
    }

    public static function getDepartmentUsers($departmentId)
    {
        $list = self::$app->user->getDepartmentUsers($departmentId, true);
        return $list;
    }

    public static function getName($id)
    {
        $ret = self::get($id)->toArray();
        return $ret['name'];
    }

    public static function getId($name)
    {
        $ret = self::get(['name'=>$name])->toArray();
        return $ret['id'];
    }

    public static function getChild(&$html,$parid,$dep)
    {
        $channels = self::field('id,name,parentid,delete_status')->select()->toArray();
        for($i = 0;$i<count($channels);$i++){
            if($channels[$i]['parentid'] == $parid)
            {
                $html[] = $channels[$i]['id'];
                self::getChild($html,$channels[$i]['id'],$dep+1);
            }
        }
    }
}
